import FileHelper from "../system/filehelper";
import SettingStore from "../storage/settingstore";
import GlobalStore from "../storage/globalstore";
import dbmysql from "../database/dbmysql";
import HandlebarsHelper from "./handlebarshelper";
import { toJava } from "./type2java";
import UTILS from "../utils/utils";
import path from "path";

/**
 * 转化为属性字段
 * @param {*} columns
 */
function toAttrList(type, columns) {
  return columns.map((value) => {
    let item = Object.assign({}, {}, value);
    item.attrName = UTILS.toFieldCase(value.columnName);
    item.attrType = toJava(value.dataType);
    item.attrComment = value.columnComment;
    item.primaryKey = value.columnKey == "PRI";
    return item;
  });
}

/**
 * 获取类型
 * @returns
 */
async function getTypes() {
  let setting = SettingStore.get();

  let dir = setting.templatePath;

  let list = FileHelper.listDirs(dir);

  return list.map((c) => {
    return path.basename(c);
  });
}

/**
 * 获取模板
 * @param {*} linkId
 * @param {*} tableId
 * @param {*} type
 * @returns
 */
async function getTemplates(linkId, tableId, type) {
  let setting = SettingStore.get();

  let global = GlobalStore.get();

  let dir = `${setting.templatePath}/${type}`;

  let table = await dbmysql.table(linkId, tableId);

  // console.log("getTemplates(linkId, tableId, type)");
  // console.log(`getTemplates(${linkId}, ${tableId}, ${type})`);
  // console.log(table);

  let list = FileHelper.loopFiles(dir).filter((c) => {
    let extname = path.extname(c);
    return extname == ".vm";
  });

  let result = [];
  for (var i = 0; i < list.length; i++) {
    let fileName = UTILS.removeSuffix(`${path.basename(list[i])}`, ".vm");

    //去除前后缀的表名
    let pureTableName = UTILS.purefix(
      `${table.tableName}`,
      global.prefix,
      global.suffix
    );

    //最后得到的文件名
    let finalFileName = UTILS.toCamelCase(`${pureTableName}_${fileName}`);

    result.push({
      id: `${type}-${i}`,
      type: `${type}`,
      name: finalFileName,
      path: list[i],
    });
  }

  return result;
}

/**
 * 获取模板
 * @param {*} linkId
 * @param {*} tableId
 * @param {*} type
 * @param {*} templateId
 */
async function getTemplate(linkId, tableId, type, templateId) {
  let templates = await getTemplates(linkId, tableId, type);

  var item = templates.find((o) => o.id === templateId);

  return item;
}

/**
 * 预览代码
 * @param {*} linkId
 * @param {*} tableId
 * @param {*} type
 * @param {*} templateId
 */
async function previewCode(linkId, tableId, type, templateId) {
  let json = await previewJson(linkId, tableId, type, templateId);

  let template = await getTemplate(linkId, tableId, type, templateId);

  return HandlebarsHelper.compile(template.path, json);
}

/**
 * 预览结构
 * @param {*} linkId
 * @param {*} tableId
 * @param {*} type
 */
async function previewJson(linkId, tableId, type, templateId) {
  let global = await GlobalStore.get();
  let table = await dbmysql.table(linkId, tableId);
  let columns = await dbmysql.columns(linkId, tableId);
  let template = await getTemplate(linkId, tableId, type, templateId);

  let json = {};

  json = Object.assign({}, json, global);
  json = Object.assign({}, json, table);
  json.className = UTILS.toCamelCase(
    UTILS.purefix(table.tableName, global.prefix, global.suffix)
  );
  json.path = json.className.toLowerCase();
  json.date = UTILS.nowDate();
  json.templateName = template.name;
  json.templatePath = template.path;
  json.templateType = template.type;
  json.attrList = toAttrList(type, columns);

  return json;
}

/**
 * 生成文件
 * @param {*} linkId
 * @param {*} tableIds
 * @param {*} type
 * @param {*} templateIds
 */
async function produceFiles(linkId, tableIds, type) {
  console.log("produceFiles(linkId, tableIds, type)");
  console.log(linkId);
  console.log(tableIds);
  console.log(type);
  var setting = SettingStore.get();

  for (var i = 0; i < tableIds.length; i++) {
    console.log("-----tableId-----");

    var tableId = tableIds[i];

    console.log(tableId);

    var templates = await getTemplates(linkId, tableId, type);

    for (var j = 0; j < templates.length; j++) {
      var template = templates[j];

      var templateCode = await previewCode(linkId, tableId, type, template.id);

      var templateDir = path.dirname(template.path);

      var offsetDir = path.normalize(
        templateDir.replace(`${setting.templatePath}`, path.sep)
      );

      var producePath = path.normalize(
        `${setting.translatePath}/${offsetDir}/${template.name}`
      );

      console.log(`file path:${producePath}`);

      await FileHelper.writeFile(producePath, templateCode);
    }
  }
  return path.normalize(`${setting.templatePath}/${type}`);
}

let TemplateHelper = {
  getTemplates,
  getTypes,
  previewCode,
  previewJson,
  produceFiles,
};

export default TemplateHelper;
